let axios = require('axios');
let cheerio = require('cheerio');
let fs = require('fs')
class taskRun {
  constructor(task,cb) {
    this.task = task;
    this.cb = cb;
    this.setting(this.task.nickname, this.task.cookie)
    this.run();
  }

  setting(userName, cookie) {
    this.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Host': 'qianka.com',
      'Cookie': cookie,
      'Accept': 'application/json, text/plain, */*',
      'User-Agent': `Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 version=2.0.2018091801 bid=com.kka.video`
    }
    this.instance = axios.create({
      baseURL: 'https://qianka.com',
      headers: this.headers
    });
  }
  async run() {
    this.applyTaskList = await this.getTaskList()
  }
  // 可申请任务列表
  async getTaskList() {
    let list=[]
    try {
      let result = await this.instance.get(`/s4/lite.subtask.list`);
      console.log(result)
    } catch (err) {
      console.error(err)
    }
    return list
  }
  taskRun(task) {
    this.getTaskList(data => {
      try {
        this.newTaskId = 0
        if (data.success) {
          let tasks = [].concat(data.res.data.payload.tasks || []).concat(data.res.data.payload.newbie || [])
          let flag = false;
          this.tasks = [];
          for (let i = 0; i < tasks.length; i++) {
            if (tasks[i].is_pay === 0) {
              this.tasks.push(tasks[i]);
            }
            if (tasks[i].status === 2) {
              flag = true;
              this.currentTaskId = tasks[i].id;
              this.currentTaskIndex = i;
            }
          }
          if (this.tasks.length && flag === false && this.tasks[0].qty > 0) {
            this.newTaskId = this.tasks[0].id;
            console.log(`发现新任务:${this.tasks[0].title}:${this.newTaskId}`);
            this.cb({
              message: `发现新任务:${this.tasks[0].title}:${this.newTaskId}`
            })
            // this.applyTask(this.newTaskId)
          } else if (flag === true) {
            console.log(`任务${this.currentTaskId}进行中...`)
            console.log(`appurl:${this.app.url}`)
            this.getTaskDetail();
            // return false;
          }
        } else {

        }
      } catch (err) {
        this.cb({
          message: err
        })
      }
    })
  }

  async liteSubtaskStart() {
    let result = await this.instance.get(`https://qianka.com/s4/lite.subtask.start?task_id=${id}&quality=0`)
  }
}
module.exports = taskRun;
